<?php

namespace Celebrio\Util;

use \Nette\Object;
use \Nette\Environment;

use Celebrio\ShadowReader;

/**
 * TwoWayCrypt performs symmetric encryption and decryption of critical entries
 * in the system, such as passwords.
 *
 * @author pavel
 */
abstract class TwoWayCrypt extends Object {

    const METHOD = "AES-256-CBC";

    private static $init_vector = "init vector00000";
    private static $key;

    public static function encrypt($data) {
        if ($data === null) return null;
        return @openssl_encrypt($data, self::METHOD, self::getKey(), null);
    }

    public static function decrypt($data) {
        if ($data === null) return null;
        $result = @openssl_decrypt($data, self::METHOD, self::getKey(), null);

        if ($result === false) {
            // backward compatibility
            // TODO check all the records and convert them if they were ciphered by null key
            // deploy -> all the passwords which end by '=' decode using null and encode using self::getKey()
            //        -> all the passwords which does NOT end by '=' only encode using self::getKey()
            $result = @openssl_decrypt($data, self::METHOD, null, null);
        }
        return $result;
    }

    private static function getKey() {
        if (self::$key === null) {
            $shadowReader = new ShadowReader();
            self::$key = $shadowReader->getPassword("twoWayEnc");
        }
        return self::$key;
    }

    private static function getInitVector() {
        return self::$init_vector;
    }
}